<template>
  <eui-background type="common">
    <eui-navbar ref="EuiNavBar" :title="title" :storeName="sUserStoreName" :storeId="sUserStore" displayable="true"/>
    <view class="top-view">
      <eui-search-bar ref="RdsSearchBar" v-model="searchText" placeholder="请输入商品条码、编码" leftIcon="icon-saoyisao"
                      @confirm="searchConfirm" @leftIconClick="clickScanRight" radius="30">
      </eui-search-bar>
    </view>
    <eui-card hPadding="28">
      <eui-card-input v-model="mainData.c_adno" title="部门" h-padding="0" type="textname"
                      :name="getRelatedName('rdsDeparts', mainData.c_adno)" ref="cardAdnoInput" isBlur alignType="left"
                      required="true" :rightIconType="detailData.length > 0 ? '' : 'right'"
                      :displayable="mainData.c_status !== '0'" @iconClick="clickRight('c_adno')"
                      @confirm="validateMain('c_adno', mainData.c_adno)"/>
      <eui-card-input v-model="mainData.c_dc_wno" title="配送仓库" h-padding="0" type="textname"
                      :name="getRelatedName('rdsWnos', mainData.c_dc_wno)" ref="cardWnoInput" isBlur alignType="left"
                      required="true" :rightIconType="detailData.length > 0 ? '' : 'right'"
                      :displayable="mainData.c_status === '0'" @iconClick="clickRight('c_dc_wno')"
                      @confirm="validateMain('c_dc_wno', mainData.c_dc_wno)"/>
      <eui-card-input v-model="mainData.c_delivery_dt" title="配送日期" placeholder="请选择日期" h-padding="0"
                      alignType="left" @input="deliverDtChanged" type="date" required="true"
                      :displayable="detailData.length > 0" :rightIconType="detailData.length > 0 ? '' : 'right'"/>
      <eui-card-input v-model="mainData.c_d_store_id" title="目的机构" h-padding="0" type="textname"
                      :name="getRelatedName('rdsStores', mainData.c_d_store_id)" ref="cardDStoreInput" isBlur
                      alignType="left" :displayable="detailData.length > 0"
                      :rightIconType="detailData.length > 0 ? '' : 'right'" @iconClick="clickRight('c_d_store_id')"
                      @confirm="validateMain('c_d_store_id', mainData.c_d_store_id)"/>
      <eui-card-input v-model="mainData.c_pl_no" title="采购基地" h-padding="0" type="textname"
                      :name="getFreshLocationName(mainData.c_pl_no)" isBlur alignType="left"
                      :displayable="detailData.length > 0" :rightIconType="detailData.length > 0 ? '' : 'right'"
                      @iconClick="clickRight('c_pl_no')" @confirm="validateMain('c_pl_no', mainData.c_pl_no)"/>
      <eui-card-input v-model="mainData.c_buyer_no" title="采购员" h-padding="0" type="textname"
                      :name="getRelatedName('rdsUsers', mainData.c_buyer_no)" isBlur alignType="left"
                      :displayable="detailData.length > 0" :rightIconType="detailData.length > 0 ? '' : 'right'"
                      @iconClick="clickRight('c_buyer_no')" @confirm="validateMain('c_buyer_no', mainData.c_buyer_no)"/>
      <eui-notice-bar single="true" scrollable="true" showIcon="true" ref="60"
                      :text="'总数量：' + c_n_buy.toFixed(2) + '，总金额：' + c_at_pay.toFixed(2) + '，品种数：' + c_sku_buy"/>
    </eui-card>
    <view class="footer-view" :style="{ height: listHeight + 'rpx' }">
      <scroll-view scroll-y="true" style="height: 100%;">
        <view style="display:flex;flex-direction: column">
          <eui-card hPadding="28" v-if="detailData && detailData.length > 0">
            <eui-swipe-action>
              <view :ref="'dataItem' + index" v-for="(item, index) in detailData" :key="index"
                    @click="onClickGdsInfo(item, index)">
                <eui-swipe-actionitem :ref="`swipeActionItem${index}`" :right-options="options" show="none"
                                      :auto-close="true" @change="change" @click="bindClick($event, index)"
                                      :disabled="mainData.c_status !== '0'">
                  <view class="item-view">
                    <eui-text type="name2" :value="index + 1 + '. ' + '[' + item.c_gcode + ']' + item.c_gname"
                              cWidth="width: 100%"/>
                    <eui-text type="price2" title="采购件数" :value="item.c_n_pack" :valueStyle="showRightStyle"
                              :precision="3"/>
                    <eui-text type="price2" title="均重" :value="item.c_avg_weight" :valueStyle="showRightStyle"
                              :precision="3"/>
                    <eui-text type="price2" title="采购价格" :value="item.c_pt_pay" :valueStyle="showRightStyle"
                              :precision="3"/>
                    <eui-text type="price2" title="最后进价" :value="item.c_last_pt_pay" :valueStyle="showRightStyle"
                              :precision="3"/>
                    <eui-text type="price2" title="采购金额" :value="item.c_at_pay" :valueStyle="showRightStyle"
                              :precision="3"/>
                    <eui-text type="price2" title="采购数量" :value="item.c_n_total_pur" :valueStyle="showRedStyle"
                              :precision="3"/>
                  </view>
                  <view class="button-view">
                    <eui-button type="min2" title="分店分货" :value="item" :font-color="'#13c2e1'"
                                border-color="transparent" single-tag="store" @buttonClick="buttonClick($event, item)"/>
                  </view>
                </eui-swipe-actionitem>
              </view>
            </eui-swipe-action>
          </eui-card>
        </view>
      </scroll-view>
    </view>
    <view class="bottom-view">
      <view class="center-style">
        <eui-button type="max2" title="保存" singleTag="save" @buttonClick="buttonClick"
                    :disabled="!(mainData.c_status === '0' && detailData.length > 0)"/>
        <view class="gap-view"/>
        <view v-if="mainData.c_status !== '0' && detailData.length > 0">
          <eui-button type="max2" title="装车信息" singleTag="info" @buttonClick="buttonClick"/>
        </view>
        <view v-if="mainData.c_status === '0' && detailData.length > 0">
          <eui-button type="max" title="装车" singleTag="submit" @buttonClick="buttonClick"/>
        </view>
      </view>
    </view>
    <eui-popup ref="gdsPopup" background-color="#f8f8f8" type="bottom" :mask-click="mainData.c_status !== '0'">
      <view class="popup-content">
        <view style="padding: 20rpx 20rpx 0 20rpx">
          <view class="item-view">
            <eui-text :value="'[' + currentGds.c_gcode + ']' + currentGds.c_gname" type="name2"
                      title="商品" cWidth="width: 100%"/>
            <eui-text :value="getName('rdsProviders', currentGds.c_provider)" type="name2" title="供应商"
                      cWidth="width: 100%"/>
            <eui-text :value="getName('rdsDeparts', currentGds.c_adno)" type="name2" title="部门" cWidth="width: 100%"/>
            <eui-text :value="currentGds.c_n_inv_dc" type="price2" title="库存数量" :valueStyle="showRightStyle"
                      :precision="3"/>
            <eui-text :value="currentGds.c_n_om" type="price2" title="已分配数量" :valueStyle="showRightStyle"
                      :precision="3"/>
            <eui-text :value="currentGds.c_n_orig_req" type="price2" title="请求数量" :valueStyle="showRightStyle"
                      :precision="3"/>
            <eui-text :value="currentGds.c_last_pt_pay" type="price2" title="最后进价" :valueStyle="showRightStyle"
                      :precision="3"/>
          </view>
          <view class="item-view" v-if="mainData.c_status !== '0'">
            <eui-text :value="getDictName('物流模式', currentGds.c_d_type)" type="name2" title="物流模式"/>
            <eui-text :value="getDictName('越库类型', currentGds.c_s_mode)" type="name2" title="越库类型"/>
            <eui-text :value="currentGds.c_avg_weight" type="price2" title="均重" :valueStyle="showRightStyle"
                      :precision="3"/>
            <eui-text :value="currentGds.c_avg_tare" type="price2" title="单件皮重" :valueStyle="showRightStyle"
                      :precision="3"/>
            <eui-text :value="currentGds.c_pt_pay" type="price2" title="采购价格" :valueStyle="showRightStyle"
                      :precision="3"/>
            <eui-text :value="currentGds.c_n_total_pur" type="price2" title="采购数量" :valueStyle="showRightStyle"
                      :precision="3"/>
            <eui-text v-model="currentGds.c_note" type="name2" title="备注" cWidth="width: 100%; margin-bottom: 20rpx"
                      :valueStyle="noteStyle"/>
          </view>
          <view v-if="mainData.c_status === '0'">
            <eui-card-input v-model="currentGds.c_d_type" title="物流模式" :range="dTypeSelectList" h-padding="0"
                            alignType="left" type="radio" rightIconType="right" @buttonClick="dTypeInput"/>
            <eui-card-input v-model="currentGds.c_s_mode" title="越库类型" :range="sModeSelectList" h-padding="0"
                            alignType="left" type="radio" :displayable="currentGds.c_d_type !== '2'"
                            rightIconType="right"/>
            <eui-card-input v-model="currentGds.c_avg_weight" type="number" title="均重" h-padding="0"
                            fieldName="c_avg_weight" @confirm="validateDetail" isBlur ref="cardAvgWeightInput"
                            maxlength="9" alignType="left" :precision="3"/>
            <eui-card-input v-model="currentGds.c_avg_tare" type="number" title="单件皮重" h-padding="0"
                            fieldName="c_avg_tare" @confirm="validateDetail" isBlur ref="cardAvgTareInput"
                            maxlength="9" alignType="left" :precision="3"/>
            <eui-card-input v-model="currentGds.c_n_pack" type="number" title="采购件数" h-padding="0"
                            fieldName="c_n_pack" @confirm="validateDetail" isBlur ref="cardNPackInput"
                            maxlength="9" alignType="left" :precision="3"/>
            <eui-card-input v-model="currentGds.c_pt_pay" type="number" title="采购价格" h-padding="0"
                            fieldName="c_pt_pay" @confirm="validateDetail" isBlur ref="cardPtPayInput"
                            maxlength="9" alignType="left" :precision="3" required="true"/>
            <eui-card-input v-model="currentGds.c_n_total_pur" type="number" title="采购数量" h-padding="0"
                            fieldName="c_n_total_pur" @confirm="validateDetail" isBlur ref="cardNInput"
                            maxlength="9" alignType="left" :precision="3" required="true" placeholder="请输入数量"/>
            <eui-card-input v-model="currentGds.c_at_pay" type="number" title="采购金额" h-padding="0"
                            fieldName="c_at_pay" @confirm="validateDetail" isBlur ref="cardAtPayInput"
                            maxlength="9" alignType="left" :precision="3"/>
            <eui-card-input v-model="currentGds.c_note" title="备注" fieldName="c_note" h-padding="0"
                            maxlength="100" alignType="left"/>
          </view>
        </view>
        <view class="popup-bottom flex-1 flex">
          <eui-button type="max2" title="关闭" singleTag="cancel" @buttonClick="buttonClick"/>
          <eui-button type="max" title="确认" singleTag="confirm" @buttonClick="buttonClick"
                      :disabled="mainData.c_status !== '0'"/>
        </view>
      </view>
    </eui-popup>
  </eui-background>
</template>

<script setup type="ts">
import {onMounted, ref, reactive} from "vue";
import {onLoad} from "@dcloudio/uni-app";
import {validateStores, validateGds, defaultMapping, validateStoresAndWno} from '@/hooks/useValidateMethod';
import service from "@/common/service";
import {getRdsUrl, rdsRequest,} from '@/hooks/rdsServices';
import {calcAtInByPt, round} from '@/hooks/useCalculateMethod';
import {useMainStore} from "@/store/modules/store";
import {
  getRelatedName,
  getDictName,
  getFreshLocationName,
  getDictSelectList,
} from '../components/RelatedName.js';
import {getRdsUserDepartAuthority, getRdsSysConfig} from '@/hooks/init';
import dateRangUtil from "@/common/dateRangUtil";
import {validateAdnoLevel} from '@/hooks/useBillInfo';
import Enjoy from "@/common/enjoy";
const rdsUrl = getRdsUrl();
const isOpened = ref('none');
const mainStore = useMainStore();
const listHeight = ref(300);
const noteStyle = ref('white-space: nowrap;overflow: hidden;text-overflow: ellipsis');
const c_id = ref(''); //单据号
const sUserStore = ref('');
const sUserStoreName = ref('');
const sUser = ref('');
const title = ref('生鲜采购');
const searchText = ref('');
const options = ref([{
  text: '删除',
  style: {
    backgroundColor: '#F56C6C',
  }
}]);
const showRightStyle = ref('text-align: right');
const showRedStyle = ref('text-align: right;color: #FF4000;');
const sysConfig = ref({
  isBarcode: 0, // 0-否 1-是，默认为否，是：启用时则支持按箱码订货，否则不支持按箱码订货
  isStrict: '2',//0-不控制，1-严格控制，2-提示但不控制
});
const dTypeSelectList = ref([]);
const sModeSelectList = ref([]);
const detailData = ref([]);
let delList = reactive([]);
let newList = reactive([]);
let modifiedList = reactive([]);
const currentGds = ref({});
const currentGdsIndex = ref(0);
const mainData = ref({
  c_tenant_id: '',
  c_id: '',
  c_bill_type: '5C1',
  c_status: '0',
  c_delivery_dt: dateRangUtil.getCurrentDayBegin(),
  c_dc_store_id: sUserStore.value,
  c_d_store_id: sUserStore.value,
  c_store_name: sUserStore.value,
  c_dc_wno: '00',//配送中心仓库
  c_wave: '',
  c_pl_no: '',//采购地
  c_adno: '',
  c_buyer_no: sUser.value,
  c_d_type: '2',
  c_org_no: '',
  c_charge_userno: '',
  c_mk_store_id: sUserStore.value,
  c_mk_store_name: sUserStoreName.value,
  c_mk_dt: dateRangUtil.formatDate(),
  c_mk_userno: sUser.value,
  c_modify_userno: '',
  c_approve_status: '1',
  c_au_dt: null,
  c_au_userno: '',
  c_print_userno: '',
  c_print_n: 0,
  c_src_id: '',
  c_src_type: '',
  c_note: '',
  c_sys_note: ''
});
const currentPage = ref(1);
const gdsPopup = ref(null);
const RdsSearchBar = ref(null);
const cardNInput = ref(null);
const cardNPackInput = ref(null);
const cardPtPayInput = ref(null);
const cardAtPayInput = ref(null);
const cardAvgTareInput = ref(null);

const c_n_buy = ref(0);
const c_at_pay = ref(0);
const c_sku_buy = ref(0);

onMounted(() => {
  getListHeight()
})

// 获取列表高度
const getListHeight = async () => {
  await uni.getSystemInfo({
    success: function (res) { // res - 各种参数
      let info = uni.createSelectorQuery().select(".footer-view");
      info.boundingClientRect(function (data) { //data - 各种参数
        //获取列表高度
        let height = res.windowHeight - data.top;
        //转换rpx
        listHeight.value = height / (res.windowWidth / 750) - 100;
      }).exec()
    }
  });
};

onLoad(async (option) => {
  const result = await validateStores(
      {fieldName: 'c_store_id', row: {}, newValue: option.storeId},
      {ischecklimit: true, firstValueMode: true}
  );
  if (['3'].includes(result?.c_type)) {
    await setDefault({
      sUserStore: result.c_id,
      sUserStoreName: result.c_sname
    });
    sUserStore.value = option.storeId;
    mainData.value.c_dc_store_id = option.storeId;
    c_id.value = option.c_id;
    mainData.value.c_id = option.c_id;
    if (option.c_id) {
      title.value = option.c_id + '详情'
      service.enjoyShowLoading("正在加载...")
      await billQuery();
      service.enjoyHideLoading();
    }
    dTypeSelectList.value = getDictSelectList('物流模式');
    sModeSelectList.value = getDictSelectList('越库类型');
  } else {
    setTimeout(() => {
      clickRight('c_dc_store_id')
    }, 1000);
  }
  await getSysConfig();
})

const setDefault = async (storeInfo) => {
  const {loginInfo} = mainStore;
  sUserStore.value = storeInfo?.sUserStore || loginInfo.sUserStore;
  sUserStoreName.value = storeInfo?.sUserStoreName || loginInfo.sUserStoreName;
  sUser.value = loginInfo.sUser;
  mainData.value.c_store_id = storeInfo?.sUserStore || loginInfo.sUserStore;
  mainData.value.c_mk_store_id = storeInfo?.sUserStore || loginInfo.sUserStore;
  mainData.value.c_mk_userno = loginInfo.sUser;
  //验证部门层级
  if (!c_id.value) {
    if (!loginInfo.sCurrentAdno) {
      return;
    }
    const result = await validateAdnoLevel({
      IuputData: loginInfo.sCurrentAdno,
      billKind: "5C",
      tenantId: loginInfo.idsToken.tenantid
    });
    if (result && !result.HasException) {
      const userAdno = await getRdsUserDepartAuthority();
      if (userAdno.includes(loginInfo.sCurrentAdno)) {
        mainData.value.c_adno = loginInfo.sCurrentAdno;
      }
    }
  }
}

const getSysConfig = async () => {
  sysConfig.value.isBarcode = await getRdsSysConfig("进销存管理参数", "是否支持按箱码订货");
  sysConfig.value.isStrict = await getRdsSysConfig("供应链管理参数", "补货申请单门店补货量大于配送中心库存量是否严格控制");
}

// 扫码
const clickScanRight = () => {
  uni.scanCode({
    success: async function (res) {
      if (res.result != '' && res.result != undefined) {
        searchText.value = res.result;
        await searchConfirm({
          value: res.result
        });
      }
    }
  });
}

const deliverDtChanged = (value) => {
  let nowDate = dateRangUtil.getCurrentDayBegin();
  if (value < nowDate) {
    uni.showToast({
      duration: 3500,
      icon: 'none',
      title: '配送日期不能小于今天，请检查！'
    })
    setTimeout(() => {
      mainData.value.c_delivery_dt = nowDate;
    }, 200)
    return;
  }
}

const validateDetail = async (args) => {
  const {fieldName, oldValue, newValue} = args;
  switch (fieldName) {
    case 'c_n_pack':
      if (newValue >= 0 && newValue < 99999) {
        currentGds.value.c_n_pack = newValue;
        if (currentGds.value.c_n_total_pur > 0 && currentGds.value.c_n_pack > 0) {
          currentGds.value.c_avg_weight = round(currentGds.value.c_n_total_pur / newValue, 3) || 0;
          calcRowAmount(currentGds.value);
          return;
        }
        if (currentGds.value.c_avg_weight > 0 && currentGds.value.c_n_pack > 0) {
          currentGds.value.c_n_total_pur = round(currentGds.value.c_n_pack * currentGds.value.c_avg_weight, 2) || 0;
          calcRowAmount(currentGds.value);
          return;
        }
      } else {
        if (oldValue) {
          cardNPackInput.value.inputValue = oldValue;
          currentGds.value.c_n_pack = oldValue;
        }
        await uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '请输入0~99999的数'
        });
        return;
      }
      break;
    case 'c_n_total_pur':
      if (newValue >= 0 && newValue < 99999) {
        currentGds.value.c_n_total_pur = newValue;
        if (currentGds.value.c_n_pack * 1 == 0 && currentGds.value.c_avg_weight * 1 != 0) {
          currentGds.value.c_n_pack = round(currentGds.value.c_n_total_pur / currentGds.value.c_avg_weight, 3) || 0;
        }
        if (currentGds.value.c_n_pack * 1 != 0) {
          currentGds.value.c_avg_weight = round(currentGds.value.c_n_total_pur / currentGds.value.c_n_pack, 3) || 0;
        }
        //输入采购数量时，有单价时优先用单价算数量，没有单价且有金额时反算单价
        if (currentGds.value.c_pt_pay && currentGds.value.c_pt_pay > 0) {
          calcRowAmount(currentGds.value);
        } else {
          if (currentGds.value.c_at_pay && currentGds.value.c_at_pay > 0 && currentGds.value.c_n_total_pur > 0) {
            currentGds.value.c_pt_pay = round(currentGds.value.c_at_pay / currentGds.value.c_n_total_pur, 2) || 0;
          }
        }
      } else {
        if (oldValue) {
          cardNInput.value.inputValue = oldValue;
          currentGds.value.c_n_total_pur = oldValue;
        }
        await uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '请输入0~99999的数'
        });
      }
      break;
    case 'c_pt_pay':
      if (newValue >= 0 && newValue < 99999) {
        currentGds.value.c_pt_pay = newValue;
        calcRowAmount(currentGds.value);
      } else {
        if (oldValue) {
          cardPtPayInput.value.inputValue = oldValue;
          currentGds.value.c_pt_pay = oldValue;
        }
        await uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '请输入0~99999的数'
        });
      }
      break;
    case 'c_at_pay':
      if (newValue >= 0 && newValue < 99999) {
        currentGds.value.c_at_pay = newValue;
        if (currentGds.value.c_n_total_pur > 0) {
          currentGds.value.c_pt_pay = round(currentGds.value.c_at_pay / currentGds.value.c_n_total_pur, 2) || 0;
        } else if (currentGds.value.c_pt_pay > 0) {
          currentGds.value.c_n_total_pur = round(currentGds.value.c_at_pay / currentGds.value.c_pt_pay, 2) || 0;
        }
      } else {
        if (oldValue) {
          cardAtPayInput.value.inputValue = oldValue;
          currentGds.value.c_at_pay = oldValue;
        }
        await uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '请输入0~99999的数'
        });
      }
      break;
    case 'c_avg_tare':
      if (newValue >= 0) {
        currentGds.value.c_avg_tare = newValue;
      } else {
        if (oldValue) {
          cardAvgTareInput.value.inputValue = oldValue;
          currentGds.value.c_avg_tare = oldValue;
        }
        await uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '请输入大于0的数'
        });
      }
      break;
  }
}

const buttonClick = async (t, item) => {
  let {singleTag} = t;
  switch (singleTag) {
    case 'save':
      // 保存
      if (detailData.value.length <= 0) {
        await uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '商品不能为空！'
        });
        return;
      }
      service.enjoyShowLoading('正在保存...');
      await saveBill();
      await billQuery();
      service.enjoyHideLoading();
      break;
    case 'submit':
      // 装车
      if (detailData.value.length <= 0) {
        await uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '商品不能为空！'
        });
        return;
      }
      service.enjoyShowLoading('正在保存...');
      await saveBill();
      service.enjoyHideLoading();
      setTimeout(() => {
        uni.navigateTo({
          url: '../FreshLoad/edit?c_src_id=' + mainData.value.c_id
        });
      }, 300);
      break;
    case 'info':
      // 装车展示
      await uni.navigateTo({
        url: '../FreshLoad/index?c_src_id=' + mainData.value.c_id
      });
      break;
    case 'cancel':
      gdsPopup.value.close();
      RdsSearchBar.value.clear();
      break;
    case 'confirm':
      service.enjoyShowLoading("正在加载...");
      currentGds.value.rowType = (currentGds.value.rowType === 1 || currentGds.value.rowType === undefined) ? 1 : 2;
      detailData.value[currentGdsIndex.value] = currentGds.value;
      service.enjoyHideLoading();
      setTimeout(() => {
        gdsPopup.value.close();
        RdsSearchBar.value.clear();
        calcMainAmount();
      }, 300);
      break;
    case 'store':
      // 分店分货
      service.enjoyShowLoading("正在加载...");
      if (mainData.value.c_status === '0') {
        await saveBill();
      }
      service.enjoyHideLoading();
      setTimeout(() => {
        uni.navigateTo({
          url: './store?c_id=' + mainData.value.c_id + '&c_gcode=' + item.c_gcode + '&c_gname=' + item.c_gname
        });
      }, 300);
      break;
  }
}

const saveBill = async () => {
  if (detailData.value.length <= 0) {
    await uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '请录入商品！'
    });
    return;
  }
  let flag = mainData.value.c_id;
  if (!flag) {
    const getBilIdReq = {
      BillIdKeyValue: {
        key: "c_id",
        value: ""
      },
      BillVariable: "",
      TableName: "tb_po_fsh_po",
      BillName: "生鲜采购单"
    }
    const billId = await rdsRequest(rdsUrl.mainApi, '单号生成服务', 'EnjoyGetBillId', getBilIdReq, '5C1');
    if (billId) {
      mainData.value.c_mk_userno = sUser.value;
      mainData.value.c_mk_store_id = sUserStore.value;
      mainData.value.c_id = billId;
      title.value = billId + '详情';
    }
  } else {
    mainData.value.c_req_userno = sUser.value;
    mainData.value.c_modify_userno = sUser.value;
    mainData.value.c_modify_dt = dateRangUtil.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss');
  }

  detailData.value.forEach(x => x.c_id = mainData.value.c_id)
  newList = detailData.value.filter(x => x.rowType == 1 || !x.hasOwnProperty('rowType'));
  modifiedList = detailData.value.filter(x => x.rowType == 2);
  const req = {
    NewList: flag ? [] : [mainData.value],
    ModifiedList: flag ? [mainData.value] : [],
    DelList: [],
    TableName: "tb_po_fsh_po",
    PrimaryKeys: ["c_tenant_id", "c_id"],
    ChildData: [{
      ChildTableName: "tb_po_fsh_pog",
      ParentTableName: "tb_po_fsh_po",
      ChildColumnNames: ["c_id"],
      ParentColumnNames: ["c_id"],
      ChildSaveModel: {
        NewList: newList,
        ModifiedList: modifiedList,
        DelList: delList,
        TableName: "tb_po_fsh_pog",
        PrimaryKeys: ["c_tenant_id", "c_id", "c_sort"],
      },
    }],
    BillSet: {
      BillIdKeyValue: {
        key: "c_id",
        value: mainData.value.c_id
      },
      BillVariable: "",
      TableName: "tb_po_fsh_po",
      BillName: "生鲜采购单"
    },
  };
  await rdsRequest(rdsUrl.scApi, '生鲜采购单', 'EnjoyBillSaveNew', req, '5C1');
  await uni.showToast({
    duration: 2000,
    icon: 'none',
    title: `保存成功`
  });
  detailData.value.forEach(x => {
    x.rowType = 2;
  })
  newList = [];
  modifiedList = [];
  delList = [];
}

const billQuery = async () => {
  if (!mainData.value.c_id) {
    return;
  }
  service.enjoyShowLoading('正在加载...');
  const req = {
    BillId: mainData.value.c_id,
  };
  const result = await rdsRequest(rdsUrl.scApi, '生鲜采购单', 'EnjoyBillQuery', req, '5C1');
  if (result.ds.length > 0) {
    mainData.value = result.ds[0];
    detailData.value = result.ds1;
    detailData.value.forEach(x => {
      x.rowType = 2;
    })
    title.value = mainData.value.c_id + '详情';
    calcMainAmount();
  } else {
    await uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '未查询到数据',
      mask: true,
    });
  }
}

const searchConfirm = async (e) => {
  if (!e || !e.value) {
    return;
  }
  let searchValue = e.value;
  if (!mainData.value.c_adno) {
    await uni.showToast({
      title: '请先选择部门！',
      icon: 'none',
      duration: 2000,
    });
    setTimeout(() => {
      clickRight('c_adno');
    }, 1000);
    return;
  }
  if (!mainData.value.c_dc_store_id) {
    await uni.showToast({
      title: '请先选择配送中心！',
      icon: 'none',
      duration: 2000,
    });
    setTimeout(() => {
      clickRight('c_dc_store_id');
    }, 1000);
    return;
  }
  if (!mainData.value.c_dc_wno) {
    await uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '请先选择仓库！'
    });
    setTimeout(() => {
      clickRight('c_dc_wno');
    }, 1000);
    return;
  }
  let barCode = '';
  if (searchValue.length == 7) {
    const gdsInfo = await getGdsInfo(searchValue);
    barCode = gdsInfo?.c_barcode;
  } else {
    barCode = searchValue;
  }
  searchText.value = searchValue;
  const itemIndex = detailData.value.findIndex(i => i.c_barcode && i.c_barcode == barCode);
  if (itemIndex !== -1) {
    service.enjoyShowLoading('正在加载...');
    // //计算当前商品所在页数
    // const page = Math.ceil(itemIndex / 10);
    // //如果商品所在页数大于当前页数，刷新到当前页数
    // if (this.currentPage < page) {
    //   this.currentPage = page;
    //   this.$refs.paging.refreshToPage(Math.ceil(itemIndex / 10));
    // }
    // setTimeout(() => {
    //   //定位到当前商品
    //   this.$refs.paging.scrollIntoViewById(`item-${itemIndex}`, 300, true);
    // }, 300);
    onClickGdsInfo(detailData.value[itemIndex], itemIndex)
    service.enjoyHideLoading();
  } else {
    if (mainData.value.c_status != '0') {
      const itemIndex = detailData.value.findIndex(i => i.c_barcode && i.c_barcode == barCode);
      if (itemIndex !== -1) {
        // service.enjoyShowLoading('正在加载...');
        // //计算当前商品所在页数
        // const page = Math.ceil(itemIndex / 10);
        // //如果商品所在页数大于当前页数，刷新到当前页数
        // if (this.currentPage < page) {
        //   this.currentPage = page;
        //   this.$refs.paging.refreshToPage(Math.ceil(itemIndex / 10));
        // }
        // setTimeout(() => {
        //   //定位到当前商品
        //   this.$refs.paging.scrollIntoViewById(`item-${itemIndex}`, 300, true);
        // }, 300);
        // service.enjoyHideLoading();
      } else {
        await uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '未查询到商品'
        });
      }
      return;
    }
    currentGds.value = initRow();
    let args = {fieldName: 'c_gcode', row: currentGds.value, newValue: searchText.value,};
    service.enjoyShowLoading('正在加载...');
    const result = await validateGds({
      uniqueKey: '生鲜采购单', billType: '5C1', args,
      head: {
        code: sUserStore.value,
        adno: mainData.value.c_adno,
        login_store: sUserStore.value,
        provider: currentGds.value.c_provider,
        con_no: currentGds.value.c_con_no,
        wno: mainData.value.c_dc_wno,
      },
      listManager: detailData.value,
      mapping: [
        ...defaultMapping,
        //分店信息
        ['c_tax_rate', 'c_tax_rate'],
        ['c_type', 'c_g_type'],
        ['c_barcode', 'c_barcode'],
        ['c_move_unit', 'c_distr_unit', 'c_order_unit', 'c_basic_unit'],//单位
        ['c_move_pack', 'c_distr_content', 'c_order_content', 'c_n_total_pur'],//包装
        //采购信息
        ['c_con_no', 'c_con_no'],
        ['c_provider', 'c_provider'],
        ['c_con_type', 'c_con_type'],
        ['c_pt_pay', 'c_pt_in'], //采购价格
        ['c_last_pt_pay', 'c_last_pt_in'], //最后进价
        ['c_pt_pay', 'c_pt_pay'],
        ['c_pet_pay', 'c_pet_pay'],
        ['c_tax_src', 'c_tax_src'],
        ['c_dc_store_id', 'c_dc_store_id'],
        ['c_dc_wno', 'c_dc_wno'],
        //合同信息
        ['c_pay_type', 'c_pay_type'],           //结算方式
        ['c_tax_rate_pay', 'c_tax_rate_pay'],   //结算税率


        //商品分店信息统计信息
        ['c_n_total_pur', ''],
        //库存信息
        ['c_n_inv_dc', 'c_n_inv'],
      ],
      initRow: initRow,
      callback: async (items) => {
        items.forEach(item => {
          item.c_n_inv = item.c_n_inv == null ? 0 : item.c_n_inv;
          item.c_last_pt_in = item.c_last_pt_in == null ? 0 : item.c_last_pt_in;
        })
        return true;
      }
    })
    if (result) {
      currentGdsIndex.value = detailData.value.findIndex(i => i.c_barcode && i.c_barcode === barCode);
      onClickGdsInfo(detailData.value[currentGdsIndex.value], currentGdsIndex.value);
      // setTimeout(() => {
      //   //计算当前商品所在页数
      //   const page = Math.ceil(this.currentGdsIndex / 10);
      //   //如果商品所在页数大于当前页数，刷新到当前页数
      //   if (this.currentPage < page) {
      //     this.currentPage = page;
      //     this.$refs.paging.refreshToPage(page);
      //   }
      //   //定位到当前商品
      //   this.$refs.paging.scrollIntoViewById(`item-${this.currentGdsIndex}`, 300, true);
      // }, 300);
    }
    service.enjoyHideLoading();
  }
}

const getGdsInfo = async (gcode) => {
  const req = {
    WhereList: [
      {c_col: "c_store_id", c_oper: "等于", c_value: mainData.value.c_dc_store_id, c_logic: "而且"},
      {c_col: "inputOrigMode", c_logic: "而且", c_value: "1", c_oper: "等于"},
      {c_col: "c_gcode", c_oper: "等于", c_value: gcode, c_logic: "而且"}
    ]
  };
  const result = await rdsRequest(rdsUrl.bcApi, '弹窗通用查询', 'FetchComplexGds', req);
  if (result.ReturnObject.length > 0) {
    return result.ReturnObject[0]
  }
};

const getName = (key, value) => {
  if (!value) {
    return ''
  }
  let list = [];
  value.split(',').map(item => {
    list.push("[" + item + "]" + (getRelatedName(key, item) || key));
  })
  return list.join(',');
}

const calcRowAmount = (row) => {
  row.c_at_pay = calcAtInByPt({c_pt: row.c_pt_pay, c_n: row.c_n_total_pur});
}

const calcMainAmount = () => {
  c_sku_buy.value = detailData.value.length || 0;
  c_n_buy.value = detailData.value.reduce((pre, current) => pre + (current.c_n_total_pur ?? 0), 0);
  c_at_pay.value = detailData.value.reduce((pre, current) => pre + current.c_at_pay, 0);
}

const initRow = (index) => {
  const sort = Math.max(0, ...detailData.value.map(f => f.c_sort)) + 1 + (index || 0);
  return {
    c_tenant_id: '',
    c_id: '',
    c_sort: sort,
    c_gcode: '',
    c_provider: '',
    c_gname: '',
    c_n_inv_dc: 0,
    c_orig_n_req: 0,
    c_n_total_req: 0,
    c_n_pack: 0,
    c_avg_weight: 0,
    c_avg_tare: 0,
    c_n_total_pur: 0,
    c_n_om: 0,
    c_n_orig_req: 0,
    c_last_pt_pay: 0,
    c_pt_pay: 0,
    c_at_pay: 0,
    c_d_type: '',
    c_s_mode: '',
    c_load_process: '',
    c_n_loaded: 0,
    c_load_ids: '',
    c_mk_dt: dateRangUtil.formatDate(),
    c_modify_dt: null,
    c_note: '',
    rowType: 1,
  }
}

const onClickGdsInfo = (item, index) => {
  service.enjoyShowLoading('正在加载...');
  try {
    currentGdsIndex.value = index;
    currentGds.value = JSON.parse(JSON.stringify(item));
    currentGds.value.rowType = (currentGds.value.rowType === 1 || currentGds.value.rowType === undefined) ? 1 : 2;
    gdsPopup.value.open();
  } catch (error) {
    service.enjoyHideLoading();
  }
  service.enjoyHideLoading();
}

const clickRight = (type) => {
  if (type == 'c_pl_no') {
    uni.navigateTo({
      url: `../modals/plno/index`
    });
    return;
  }

  let params = Enjoy.GetDialogParms();
  params.CallBack = ChangeCallBack;
  switch (type) {
    case 'c_dc_store_id':
      params.CallBack = dcStoreCallBack;
      params.SelectionType = "机构选择";
      params.SelectedItems = mainData.value.c_dc_store_id;
      break;
    case 'c_adno':
      params.SelectionType = "部门选择";
      params.SelectedItems = mainData.value.c_adno;
      break;
    case 'c_dc_wno':
      params.SelectionType = '仓库选择';
      params.SelectedItems = mainData.value.c_dc_wno;
      params.SelectionStoreId = mainData.value.c_dc_store_id;
      break;
    case 'c_d_store_id':
      params.SelectionType = "机构选择";
      params.SelectedItems = mainData.value.c_d_store_id;
      break;
    case 'c_buyer_no':
      params.SelectionType = '人员选择';
      params.SelectedItems = mainData.value.c_buyer_no;
      break;
  }
  Enjoy.OpenDialog(params);
}

const ChangeCallBack = async (event) => {
  if (event.SelectionType == '机构选择') {
    mainData.value.c_d_store_id = event.BackParms.Key;
  } else if (event.SelectionType == '仓库选择') {
    mainData.value.c_dc_wno = event.BackParms.Key;
  } else if (event.SelectionType == '人员选择') {
    mainData.value.c_buyer_no = event.BackParms.Key;
  } else if (event.SelectionType == '部门选择') {
    mainData.value.c_adno = event.BackParms.Key;
  }
}

const dcStoreCallBack = async (e) => {
  let curStoreId = e.BackParms.Key;
  const result = await validateStoresAndWno({value: curStoreId, wno: mainData.value.c_dc_wno});
  if (result) {
    const result = await validateStores(
        {fieldName: 'c_store_id', row: mainData.value, newValue: curStoreId},
        {ischecklimit: true, firstValueMode: true}
    );
    if (['3'].includes(result.c_type)) {
      // 更新机构信息
      sUserStoreName.value = e.BackParms.Value;
      sUserStore.value = curStoreId;
      mainData.value.c_dc_store_id = curStoreId;
      mainData.value.c_mk_store_id = curStoreId;
    } else {
      await uni.showToast({
        duration: 3500,
        icon: 'none',
        title: '请选择配送中心！'
      });
      setTimeout(() => {
        clickRight('c_dc_store_id')
      }, 300);
    }
  } else {
    mainData.value.c_dc_wno = '';
  }
}

const SelectionChanged = async (type, param) => {
  switch (type) {
    case 'wno':
      mainData.value.c_dc_wno = param.c_wno;
      break;
    case 'plno':
      mainData.value.c_pl_no = param.c_no;
      break;
    case 'user':
      mainData.value.c_buyer_no = param.c_userno;
      break;
    case 'depart':
      mainData.value.c_adno = param.c_adno;
      break;
  }
}

const validateMain = async (t, e) => {
  switch (t) {
    case 'c_adno':
      const lsGds = detailData.value.filter(i => i.c_gcode?.length > 0);
      if (lsGds.length > 0 && lsGds.some(i => !i.c_adno.startsWith(e))) {
        await uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '录入部门与明细商品部门不匹配！'
        });
        return;
      }
      break;
  }
};

const dTypeInput = (value) => {
  if (value !== '2') {
    currentGds.value.c_s_mode = '';
  } else {
    currentGds.value.c_s_mode = '1';
  }
}

const change = (e) => {
  isOpened.value = e;
}

const bindClick = (e, index) => {
  uni.showModal({
    title: ' 提示',
    content: '您确定要删除数据吗？',
    showCancel: true,
    success: async (res) => {
      if (res.confirm) {
        let gdsData = detailData.value[index];
        if (gdsData.rowType === 2) {
          delList.push(gdsData);
        }
        detailData.value.splice(index, 1);
        calcMainAmount();
      }
    }
  });
}

defineExpose({
  SelectionChanged
});
</script>

<style lang="scss" scoped>
@import '../../../main.scss';

.top-view {
  width: 100%;
  height: 88rpx;
}

.extra-view {
  margin-right: 30rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 60rpx;
  height: 100%;
}

.footer-view {
  width: 100%;
  flex: 1;
}

.list-scroll {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

.bottom-view {
  width: 100%;
  height: 100rpx;
  background: #FFFFFF;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  flex-direction: row;
}

.center-style {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  margin-right: 20rpx;
  //gap: 20rpx;
}

.gap-view {
  width: 20rpx;
  height: auto;
}

//内容行
.item-view {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  align-items: center;
  margin-top: 16rpx;
  row-gap: 8rpx;
}

.button-view {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-top: 16rpx;
  row-gap: 8rpx;
}

.line-view {
  width: 100%;
  height: 1rpx;
  background: #EEEEEE;
  margin: 20rpx 0;
}

.popup-content {
  align-items: center;
  justify-content: left;
  flex-direction: column;
  padding: 0;
  width: 100%;
  background-color: #ffffff;
}

.popup-bottom {
  background: #ffffff;
  border-top: 1rpx solid $uni-line-color;
  display: flex;
  justify-content: center;
  padding: 20rpx;
}
</style>
